package ws_print

import (
	"github.com/togettoyou/wsc"
	"log"
	"net/url"
	"print-link/fw_log"
	"time"
)

var WsClient *wsc.Wsc

func StartWsClient() {
	WsClient = wsc.New("ws://localhost:12346")
	// 可自定义配置，不使用默认配置
	WsClient.SetConfig(&wsc.Config{
		// 写超时
		WriteWait: 10 * time.Second,
		// 支持接受的消息最大长度，默认512字节
		MaxMessageSize: 10240,
		// 最小重连时间间隔
		MinRecTime: 2 * time.Second,
		// 最大重连时间间隔
		MaxRecTime: 60 * time.Second,
		// 每次重连失败继续重连的时间间隔递增的乘数因子，递增到最大重连时间间隔为止
		RecFactor: 1.5,
		// 消息发送缓冲池大小，默认256
		MessageBufferSize: 5120,
	})
	// 设置回调处理
	WsClient.OnConnected(func() {
		log.Println("OnConnected: ", WsClient.WebSocket.Url)
	})
	WsClient.OnConnectError(func(err error) {
		log.Println("OnConnectError: ", err.Error())
	})
	WsClient.OnDisconnected(func(err error) {
		log.Println("OnDisconnected: ", err.Error())
	})
	WsClient.OnClose(func(code int, text string) {
		log.Println("OnClose: ", code, text)
	})
	WsClient.OnTextMessageSent(func(message string) {
		//log.Println("OnTextMessageSent: ", message)
	})
	WsClient.OnBinaryMessageSent(func(data []byte) {
		log.Println("OnBinaryMessageSent: ", string(data))
	})
	WsClient.OnSentError(func(err error) {
		log.Println("OnSentError: ", err.Error())
	})
	WsClient.OnPingReceived(func(appData string) {
		log.Println("OnPingReceived: ", appData)
	})
	WsClient.OnPongReceived(func(appData string) {
		log.Println("OnPongReceived: ", appData)
	})
	WsClient.OnTextMessageReceived(func(message string) {
		decodedData, err := url.QueryUnescape(message)
		if err != nil {
			fw_log.Slogger.Infoln("返回的原始数据解析错误--->", err.Error())
			return
		}
		fw_log.Slogger.Infoln("解析后的数据--->", decodedData)
	})
	WsClient.OnBinaryMessageReceived(func(data []byte) {
		fw_log.Slogger.Infoln(string(data))
	})
	// 开始连接
	go WsClient.Connect()
}
